package com.gaogzhen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaogzhen.domain.Notice;
import com.gaogzhen.mapper.NoticeMapper;
import com.gaogzhen.service.NoticeService;
import org.springframework.transaction.annotation.Transactional;

@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService{

    @Override
    public Page<Notice> findByPage(Page<Notice> page, String title, String startTime, String endTime, Integer status) {
        page.addOrder(OrderItem.desc("last_update_time"));
        return page(page, new LambdaQueryWrapper<Notice>()
                .like(StringUtils.isNotBlank(title), Notice::getTitle, title)
                .between(!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime), Notice::getCreated, startTime, endTime + " 23:59:59")
                .eq(ObjectUtils.isNotEmpty(status), Notice::getStatus, status)
        );
        // .ge(StringUtils.isNotBlank(startTime), Notice::getCreated, DateUtils.parseDate(startTime, "yyyy-MM-dd"))
        //                .le(StringUtils.isNotBlank(endTime), Notice::getCreated, DateUtils.parseDate(endTime, "yyyy-MM-dd"))

    }

    @Override
    @Transactional
    public void delete(String[] ids) {
        if (ArrayUtils.isEmpty(ids)) {
            throw  new RuntimeException("不能为空");
        }
        boolean b = removeByIds(Arrays.asList(ids));
        if (!b) {
            throw  new RuntimeException("删除公告不能为空");
        }

    }

    @Override
    public void add(Notice notice) {
        boolean save = save(notice);
        if (!save) {
            throw new RuntimeException("新增公告管理失败!");
        }
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        if (ObjectUtils.isEmpty(status)) {
            throw new RuntimeException("状态不能为空！");
        }
        boolean update = update(new LambdaUpdateWrapper<Notice>()
                .eq(Notice::getId, id)
                .set(Notice::getStatus, status)
        );
        if (!update) {
            throw new RuntimeException("更新失败！");
        }
    }

    @Override
    public Page<Notice> findNotices(Page<Notice> page) {
        return page(page, new LambdaQueryWrapper<Notice>()
                            .eq(Notice::getStatus, 1)
                            .orderByAsc(Notice::getSort)
        );
    }
}
